/**
 * 
 */
package com.greenhouse.business.common.wraning;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.greenhouse.business.common.websocket.WarningWebsocket;
import com.greenhouse.business.domain.BizAlarmLog;
import com.greenhouse.business.domain.BizDevice;
import com.greenhouse.business.domain.BizGroup;
import com.greenhouse.business.domain.BizGroupAlarm;
import com.greenhouse.business.service.IBizAlarmLogService;

/**
 *
 * @版权 : Copyright (c) 2020 儒安物联技术研发中心
 * @author: 雷扬
 * @E-mail: leiyang@runaiot.com
 * @版本: 1.0
 * @创建日期: 2021-5-9 12:50:54
 * @ClassName WarningComputeService
 * @类描述-Description:  TODO(这里用一句话描述这个方法的作用)
 * @修改记录:
 * @版本: 1.0
 */
@Component
public class WarningComputeService {

	private Evaluator evaluator = new Evaluator();

	private Map<String, Object> env = new HashMap<String, Object>();

	@Autowired
	private IBizAlarmLogService bizAlarmLogService;

	@Autowired
	private WarningWebsocket warningWebsocket;

	public void onMessage(Long deviceId, JSONObject message, List<BizGroupAlarm> alarms, BizDevice bizDevice,
			BizGroup bizGroup) {

		List<AlarmConfig> alarmConfigs = null;

		synchronized (evaluator) {
			alarmConfigs = AlarmConfig.transFromProductWarningDTO(alarms, evaluator);
		}

		synchronized (env) {
			if (alarmConfigs.size() > 0) {
				env.put("attribute", message.getInnerMap());

				for (AlarmConfig alarmConfig : alarmConfigs) {
					boolean isAlarm = (Boolean) evaluator.execute(alarmConfig.getJexlExpression(), env);

					// 如果报警，则保存报警信息，向前端推送报警消息
					if (isAlarm) {

						BizAlarmLog log = new BizAlarmLog();

						log.setAlarmId(alarmConfig.getBizGroupAlarm().getAlarmId());

						log.setAlarmName(alarmConfig.getBizGroupAlarm().getAlarmName());

						log.setAttributeId(alarmConfig.getBizGroupAlarm().getAttributeId());

						log.setAttributeCode(alarmConfig.getBizGroupAlarm().getAttributeCode());

						log.setDeviceId(bizDevice.getDeviceId());

						log.setDeviceName(bizDevice.getDeviceName());

						log.setGroupId(bizGroup.getGroupId());

						log.setGroupName(bizGroup.getGroupName());

						log.setValue(Double.valueOf(message.getString(alarmConfig.getAttributeCode())));

						log.setCreateTime(new Date());

						bizAlarmLogService.insertBizAlarmLog(log);

						warningWebsocket.sendInfo(JSONObject.toJSONString(log));

					}

				}

			}

		}

	}
}
